import axios from 'axios'
import qs from 'qs';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCommonStore } from '@/store/common'

let useCommon

const Axios = axios.create({
  // 设置超时时间
  timeout: 10000,
})


// 请求拦截
Axios.interceptors.request.use(
  config => {
    useCommon = useCommonStore()
    if (!config.headers['Authorization'])
      config.headers['Authorization'] = useCommon.token
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
Axios.interceptors.response.use(
  response => {

  },
  error => {

  }
)


/**
 * @param url {string}      请求的URL地址
 * @param method {string}   请求方式
 * @param params  {object}  请求参数
 * @param ser  {boole}      是否是序列化
 */
export function fetch(url, method, params = {}, obj = {}, ser = false) {
  let data = {
    url,
    method,
  }
  if (method.toLocaleLowerCase() === 'get') {
    data.params = params
    if (obj.setData) data.data = obj.setData
  } else {
    data.data = ser ? qs.stringify(params) : params
    if (obj.setParams) data.params = obj.setParams
  }
  return new Promise((resolve, reject) => {
    Axios(data)
      .then(response => {
        resolve(response.data)
      })
      .catch(error=> {
        reject(error)
      })
  })
}
